package com.easyedu.core.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @author liumengran
 */
@Data
@Component
public class JwtUtils {

    public String createToken(Long userId, Long userNumber, Object level) {
        Map<String, Object> msg = new HashMap<>(8);
        msg.put("userid", userId);
        msg.put("userNumber", userNumber);
        msg.put("level", level);
        return JWT.create()
                //设置接受方信息，一般时登录用户
                .withHeader(msg)
                .withAudience("signCenter")
                //使用HMAC算法，111111作为密钥加密
                .sign(Algorithm.HMAC256("easyeduisthebestedusys"));
    }

    public Map<String, String> getMsgFromJwt(String token) {
        DecodedJWT jwt = JWT.decode(token);
        String userid = jwt.getHeaderClaim("userid").toString();
        String userNumber = String.valueOf(jwt.getHeaderClaim("userNumber"));
        String level = jwt.getHeaderClaim("level").toString();
        String serviceName = jwt.getAudience().get(0);
        Map<String, String> msg = new HashMap<>(8);
        msg.put("userid", userid);
        msg.put("level", level);
        msg.put("userNumber",userNumber);
        msg.put("serviceName", serviceName);
        return msg;
    }

}
